package com.lw.leetcode.linked.b;

import com.lw.leetcode.linked.ListNode;

/**
 * 剑指 Offer II 025. 链表中的两数相加
 * 445. 两数相加 II
 *
 * @Author liw
 * @Date 2021/8/29 22:00
 * @Version 1.0
 */
public class AddTwoNumbers2 {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    if (l1 == null && l2 == null) {
        return null;
    }
    int len1 = getLength(l1);
    int len2 = getLength(l2);
    ListNode nn;
    if (len1 > len2) {
        for (int i = 0; i < len1 - len2; i++) {
            nn = new ListNode(0);
            nn.next = l2;
            l2 = nn;
        }
    } else if (len1 < len2) {
        for (int i = 0; i < len2 - len1; i++) {
            nn = new ListNode(0);
            nn.next = l1;
            l1 = nn;
        }
    }
    ListNode add = add(l1, l2);
    if (0 == add.val) {
        add = add.next;
    }
    return add;
}


    private int getLength(ListNode l1) {
        int i = 0;
        ListNode node = l1;
        while (node != null) {
            i++;
            node = node.next;
        }
        return i;
    }

    private ListNode add(ListNode l1, ListNode l2) {
        if (l1 == null) {

            return new ListNode(0);
        }
        if (l1.next == null) {
            int i = l1.val + l2.val;
            int xi = i;
            ListNode nn;
            if (i > 9) {
                xi = i - 10;
                ListNode n = new ListNode(xi);
                nn = new ListNode(1);
                nn.next = n;
            } else {
                ListNode n = new ListNode(xi);
                nn = new ListNode(0);
                nn.next = n;
            }
            return nn;
        }
        ListNode add = add(l1.next, l2.next);
        int i = l1.val + l2.val + add.val;
        int xi = i;
        ListNode nn;
        if (i > 9) {
            xi = i - 10;
            add.val = xi;
            nn = new ListNode(1);
            nn.next = add;
        } else {
            add.val = xi;
            nn = new ListNode(0);
            nn.next = add;
        }
        return nn;
    }
}
